import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../api/api_service.dart';
import '../api/api_client.dart';
import 'user_extra_info_provider.dart';
// import 'package:workmanager/workmanager.dart';  // 暂时注释掉

class AuthState {
  final bool isLoggedIn;
  final bool isFirstLogin;
  final String? userId;
  final String? userProfile;
  final String? accessToken;
  final int? expireIn;

  const AuthState({
    this.isLoggedIn = false,
    this.isFirstLogin = true,
    this.userId,
    this.userProfile,
    this.accessToken,
    this.expireIn,
  });

  AuthState copyWith({
    bool? isLoggedIn,
    bool? isFirstLogin,
    String? userId,
    String? userProfile,
    String? accessToken,
    int? expireIn,
  }) {
    return AuthState(
      isLoggedIn: isLoggedIn ?? this.isLoggedIn,
      isFirstLogin: isFirstLogin ?? this.isFirstLogin,
      userId: userId ?? this.userId,
      userProfile: userProfile ?? this.userProfile,
      accessToken: accessToken ?? this.accessToken,
      expireIn: expireIn ?? this.expireIn,
    );
  }
}

class AuthNotifier extends StateNotifier<AuthState> {
  final ApiService _apiService = ApiService();
  UserExtraInfoNotifier? _userExtraInfoNotifier;

  AuthNotifier() : super(const AuthState());

  // 设置用户额外信息提供者引用
  void setUserExtraInfoNotifier(UserExtraInfoNotifier notifier) {
    _userExtraInfoNotifier = notifier;
  }

  Future<void> login(String username, String password) async {
    try {
      print('🌐 开始调用登录API...');

      // 调用真实的登录API
      final response = await _apiService.login(username, password);

      print('✅ 登录API调用成功');
      print('📊 响应状态码: ${response.statusCode}');
      print('📄 响应数据: ${response.data}');
      print('📋 响应头: ${response.headers}');

      // 检查响应状态
      if (response.statusCode == 200) {
        print('🎉 登录成功！');

        // 解析返回数据
        final responseData = response.data;
        if (responseData['code'] == 200) {
          final data = responseData['data'];
          final accessToken = data['access_token'];
          final expireIn = data['expire_in'];
          final userId = data['userId']?.toString();

          print('🔑 获取到Token: ${accessToken?.substring(0, 20)}...');
          print('⏰ Token过期时间: ${expireIn}秒');
          print('👤 用户ID: $userId');

          // 设置API客户端的认证token
          if (accessToken != null) {
            ApiClient().setAuthToken(accessToken);
            // 持久化保存 token
            try {
              final box = Hive.box('app');
              await box.put('accessToken', accessToken);
              if (userId != null) await box.put('userId', userId);
              if (expireIn != null) await box.put('tokenExpireIn', expireIn);
              await box.put('isLoggedIn', true);
            } catch (e) {
              // 忽略本地存储异常，仅日志提示
            }
          }

          // 登录成功后立即获取用户额外信息
          bool hasUserExtraInfo = false;
          try {
            print('🔄 登录成功后，立即获取用户额外信息...');
            final extraInfoResponse = await _apiService.getUserExtraInfo();

            if (extraInfoResponse.statusCode == 200) {
              final extraInfoData = extraInfoResponse.data;
              if (extraInfoData['code'] == 200 &&
                  extraInfoData['data'] != null) {
                // 有用户额外信息数据
                hasUserExtraInfo = true;
                print('✅ 获取到用户额外信息: ${extraInfoData['data']}');

                // 更新用户额外信息状态
                try {
                  final userExtraInfo = UserExtraInfo.fromJson(
                    extraInfoData['data'],
                  );
                  // 保存到本地并更新provider状态
                  try {
                    final box = Hive.box('app');
                    await box.put('userExtraInfo', userExtraInfo.toJson());
                    print('💾 用户额外信息已保存到本地');

                    // 更新provider状态
                    if (_userExtraInfoNotifier != null) {
                      _userExtraInfoNotifier!.state = userExtraInfo;
                      print('🔄 用户额外信息状态已更新');
                    }
                  } catch (e) {
                    print('❌ 保存用户额外信息到本地失败: $e');
                  }
                } catch (e) {
                  print('❌ 解析用户额外信息失败: $e');
                  // 即使解析失败，也认为有数据（避免重复完善档案）
                  hasUserExtraInfo = true;
                }
              } else {
                print('📭 用户额外信息为空或获取失败: ${extraInfoData['msg']}');
              }
            }
          } catch (e) {
            print('❌ 获取用户额外信息失败: $e');
          }

          // 检查是否是首次登录（根据是否有用户额外信息判断）
          final isFirstLogin = !hasUserExtraInfo;

          state = state.copyWith(
            isLoggedIn: true,
            isFirstLogin: isFirstLogin,
            userId: userId ?? username,
            accessToken: accessToken,
            expireIn: expireIn,
          );

          // 安排后台周期任务（每15分钟一次，Android 最小间隔限制）
          // try {
          //   await Workmanager().registerPeriodicTask(
          //     'periodicSyncTask',
          //     'syncBackground',
          //     frequency: const Duration(minutes: 15),
          //     initialDelay: const Duration(minutes: 5),
          //     constraints: Constraints(networkType: NetworkType.connected),
          //     existingWorkPolicy: ExistingWorkPolicy.keep,
          //   );
          // } catch (_) {}
        } else {
          print('❌ 登录失败，错误信息: ${responseData['msg']}');
          throw Exception('登录失败: ${responseData['msg']}');
        }
      } else {
        print('❌ 登录失败，状态码: ${response.statusCode}');
        throw Exception('登录失败: ${response.statusCode}');
      }
    } catch (e) {
      print('💥 登录API调用异常: $e');
      rethrow; // 重新抛出异常，让上层处理
    }
  }

  Future<void> logout() async {
    // 清除API客户端的认证token
    ApiClient().clearAuthToken();
    try {
      final box = Hive.box('app');
      await box.delete('accessToken');
      await box.delete('userId');
      await box.delete('tokenExpireIn');
      await box.put('isLoggedIn', false);
    } catch (_) {}
    state = const AuthState();

    // 取消后台任务
    // try {
    //   await Workmanager().cancelByUniqueName('periodicSyncTask');
    // } catch (_) {}
  }

  Future<void> completeProfileSetup() async {
    state = state.copyWith(isFirstLogin: false);
  }

  // 手动设置/恢复 token（例如应用重启后从本地加载）
  void setAccessToken(String token) {
    ApiClient().setAuthToken(token);
    state = state.copyWith(accessToken: token, isLoggedIn: true);
  }

  Future<bool> _checkIsFirstLogin(String username) async {
    // TODO: 从本地存储或服务器检查是否是首次登录
    // 这里暂时返回true，表示首次登录
    return true;
  }
}

final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
  return AuthNotifier();
});
